/*
 *  Copyright (C) 2011  social-tourist.org
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.socialtourist.web.client.widgets.pages;

import org.socialtourist.web.client.ContentContainer;
import org.socialtourist.web.client.widgets.SocialTouristContent;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.VerticalPanel;

/*
 * The contents of this file is based in part on the stacktrace thread
 * http://stackoverflow.com/questions/1111130/basic-file-upload-in-gwt
 * 
 * Question/Answer was provided by stacktrace users Maksim/KevMo.
 * 
 */
public class PagePictureUpload extends SocialTouristContent {

	public PagePictureUpload(ContentContainer container) {
		super(container);

		final FormPanel form = new FormPanel("");
		form.setAction(GWT.getModuleBaseURL() + "fileupload");
		form.setEncoding(FormPanel.ENCODING_MULTIPART);
		form.setMethod(FormPanel.METHOD_POST);

		VerticalPanel panel = new VerticalPanel();

		final FileUpload upload = new FileUpload();
		upload.setName("fileupload");

		panel.add(upload);
		panel.add(new Button("Submit", new ClickHandler() {
			public void onClick(ClickEvent event) {
				GWT.log("You selected: " + upload.getFilename(), null);
				form.submit();
			}
		}));

		form.addSubmitHandler(new FormPanel.SubmitHandler() {
			public void onSubmit(SubmitEvent event) {
				if (!"".equalsIgnoreCase(upload.getFilename())) {
					GWT.log("UPLOADING FILE????", null);
				} else {
					event.cancel(); 
				}

			}
		});

		form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
			public void onSubmitComplete(SubmitCompleteEvent event) {
				Window.alert(event.getResults());
			}
		});

		form.add(panel);

		initWidget(form);
	}
}
